<template>
  <div class="upload-file">
    <el-upload
      ref="uploadRef"
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
    >
      <!-- 上传按钮 -->
      <el-button size="small" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <template #tip>
        <div v-if="showTip" class="el-upload__tip">
          请上传
          <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </template>
    </el-upload>

    <!-- 文件列表 -->
    <TransitionGroup class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li v-for="(file, index) in fileList" :key="file.url" class="el-upload-list__item ele-upload-list__item-content">
        <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" type="danger" @click="handleDelete(index)">删除</el-link>
        </div>
      </li>
    </TransitionGroup>
  </div>
</template>

<script setup>
import modal from "@/plugins/modal.js"

const props = defineProps({
  modelValue: {
    type: [String, Object, Array],
    default: ''
  },
  limit: {
    type: Number,
    default: 5
  },
  fileSize: {
    type: Number,
    default: 5
  },
  fileType: {
    type: Array,
    default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf']
  },
  isShowTip: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update:modelValue'])
const uploadRef = ref(null)
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/common/Upload')
const fileList = ref([])

// 计算属性
const headers = computed(() => {
  const headers = {}
  headers[$store.user.tokenName] = $store.user.token
  return headers
})

const showTip = computed(() => {
  return props.isShowTip && (props.fileType || props.fileSize)
})

// 监听值变化
watch(
    () => props.modelValue,
    (val) => {
      if (val) {
        let temp = 1
        // 首先将值转为数组
        const list = Array.isArray(val) ? val : val.split(',')
        // 然后将数组转为对象数组
        fileList.value = list.map(item => {
          if (typeof item === 'string') {
            item = {name: item, url: item}
          }
          item.uid = item.uid || new Date().getTime() + temp++
          return item
        })
      } else {
        fileList.value = []
      }
    },
    {deep: true, immediate: true}
)

// 方法
const handleBeforeUpload = (file) => {
  // 校检文件类型
  if (props.fileType) {
    let fileExtension = ''
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
    }
    const isTypeOk = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true
      return !!(fileExtension && fileExtension.indexOf(type) > -1)

    })
    if (!isTypeOk) {
      modal.msgError(`文件格式不正确, 请上传${ props.fileType.join('/') }格式文件!`)
      return false
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      modal.msgError(`文件大小不能超过 ${ props.fileSize }MB!`)
      return false
    }
  }
  return true
}

const handleExceed = () => {
  modal.msgError(`文件数量不能超过 ${ props.limit } 个!`)
}

const handleUploadError = () => {
  modal.msgError('上传失败, 请重试')
}

const handleUploadSuccess = (res) => {
  modal.msgSuccess('上传成功')
  fileList.value.push({name: res.fileName, url: res.fileName})
  emit('update:modelValue', listToString(fileList.value))
}

const handleDelete = (index) => {
  fileList.value.splice(index, 1)
  emit('update:modelValue', listToString(fileList.value))
}

const getFileName = (name) => {
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1).toLowerCase()
  }
  return ''
}

const listToString = (list, separator = ',') => {
  let strs = ''
  for (const item of list) {
    strs += item.url.replace(baseUrl, '') + separator
  }
  return strs.length > 0 ? strs.slice(0, -separator.length) : ''
}
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
